package com.liuzhilin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuzhilin.domain.Comment;
import com.liuzhilin.service.UserService;
import com.liuzhilin.util.Response;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* 获取文章的评论
* */
@WebServlet("/userGetComments")
public class UserGetComments extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Response.setCorsHeaders(response);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        try {
            // 获取请求参数
            String writer = request.getParameter("writer");
            String title = request.getParameter("title");
            // 连接数据库并查询评论
            List<Comment> comments = UserService.getComments(writer, title);
            // 构建响应数据
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("comments", comments);

            String jsonResult = objectMapper.writeValueAsString(result);
            out.print(jsonResult);
            response.setStatus(HttpServletResponse.SC_OK);

        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\": false, \"message\": \"服务器内部错误\"}");
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response) {
        // 设置CORS响应头
        Response.setCorsHeaders(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }
}
